import Axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
import router from "@/router";
const service = Axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
}); //创建axios实例

//请求拦截器
//成功执行第一个函数 失败执行第二个函数
service.interceptors.request.use(
  (config) => {
    //注入token
    // store.getters.token =>  请求头里面
    const token = store.getters.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    //失败执行promise
    return Promise.reject(error);
  }
);

//响应拦截器(解构数据和异常)
service.interceptors.response.use(
  (response) => {
    //axios默认包裹data
    const { data, message, success } = response.data;
    if (success) {
      return data;
    } else {
      Message({ type: "error", message: message });
      return Promise.reject(new Error(message));
    }
  },
  async (error) => {
    //处理token失效部分
    if (error.response.status === 401) {
      Message({ type: "warning", message: "token失效,请重新登录！" });
      await store.dispatch("user/logout");
      //跳转至登录页
      router.push("/login");
      return Promise.reject(error);
    }
    Message({ type: "error", message: error.message });
    return Promise.reject(error);
  }
);

export default service;
